#include "junix.h"

char *program_name;
char *host=NULL;
char *service=NULL;

void proc_addinfo( struct addrinfo *info);

int main(int argc, char **argv)
{
	program_name = argv[0];

	if( argc != 3)
		err_quit("Usage:%s host service", program_name);

	struct addrinfo hints, *addr;
	host=argv[1];
	service= argv[2];
	memset( &hints, 0, sizeof(hints) );

	hints.ai_socktype = SOCK_STREAM;
	hints.ai_flags = AI_ADDRCONFIG;

	if ( getaddrinfo(host, service, &hints, &addr) )
		err_sys("getaddrinfo");
	else{ 
		proc_addrinfo(addr);
		freeaddrinfo(addr);
	}

	exit(0);
}

void proc_addrinfo( struct addrinfo *info)
{
	struct addrinfo *ai=info;

	while(ai)
	{
		fprintf(stdout, "Family:");
		switch (ai->ai_family)
		{
			case PF_INET:
				printf("IPv4\n");
				break;
			case PF_INET6:
				printf("IPv6\n");
				break;
			default:
				printf("(%d)\n", ai->ai_family);
				break;
		}

		fprintf(stdout, "Socktype:");
		switch(ai->ai_socktype)
		{
			case SOCK_STREAM:
				printf("stream\n");
				break;
			case SOCK_DGRAM:
				printf("dgram\n");
				break;
			case SOCK_RAW:
				printf("raw\n");
				break;
			default:
				printf("(%d)\n",ai->ai_socktype);
				break;
		}

		if( ai->ai_family == PF_INET || ai->ai_family == PF_INET6)
		{
			fprintf(stdout, "Protocol:");
			switch (ai->ai_protocol)
			{
				case IPPROTO_TCP:
					printf("tcp\n");
					break;
				case IPPROTO_UDP:
					printf("udp\n");
					break;
				case IPPROTO_RAW:
					printf("raw\n");
					break;
				default:
					printf("(%d)\n",ai->ai_protocol);
					break;
			}
		}

		if(ai->ai_family == PF_INET)
		{
			struct sockaddr_in *sin=(void *)ai->ai_addr;
			char buf[1024];
			if(service)
				printf("Port:%d\n",ntohs(sin->sin_port));
			if(host)
				printf("Host:%s\n",inet_ntop(AF_INET, &sin->sin_addr,buf, 1024));
		}

		if(ai->ai_canonname)
			printf("Name:%s\n", ai->ai_canonname);

		printf("\n");

		ai = ai->ai_next;
	}
}
